﻿using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client.Services;

namespace UserADGroupREST
{
    [BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
    [Guid("C3343299-924E-48A8-A8DA-E874C6767100")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    public class UserInGroup : IUserInGroup
    {
        public bool userInGroup(string userToValidate, string groupDomain, string groupToValidate)
        {
           return _userInGroup(userToValidate, groupDomain, groupToValidate);
        }

        public bool userInGroupXML(string userToValidate, string groupDomain, string groupToValidate)
        {
            return _userInGroup(userToValidate, groupDomain, groupToValidate);
        }


        internal bool _userInGroup(string userToValidate, string groupDomain, string groupToValidate)
        {
            bool isOK = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain, groupDomain);
                GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupToValidate);

                if (grp != null)
                {
                    foreach (Principal p in grp.GetMembers(true))
                    {
                        if (p.SamAccountName.ToLower() == userToValidate.ToLower())
                        {
                            grp.Dispose();
                            ctx.Dispose();
                            isOK = true;
                            break;
                        }
                    }
                    grp.Dispose();
                    ctx.Dispose();
                }

            });

            return isOK;
        }
    }
}
